package com.litong.litongjiaoyu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.litong.litongjiaoyu.controller.WxPushServiceQcl;
import com.litong.litongjiaoyu.dao.SysChatrecordDao;
import com.litong.litongjiaoyu.entity.SysChatrecord;
import com.litong.litongjiaoyu.entity.WxMaTemplateData;
import com.litong.litongjiaoyu.entity.WxMssVo;
import com.litong.litongjiaoyu.service.SysChatrecordService;
import com.litong.litongjiaoyu.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * (SysChatrecord)表服务实现类
 *
 * @author jingzepei
 * @since 2020-06-02 10:53:36
 */
@Service("sysChatrecordService")
public class SysChatrecordServiceImpl implements SysChatrecordService {
    
    private Logger logger = LoggerFactory.getLogger(SysChatrecordServiceImpl.class);
    
    
    @Resource
    private SysChatrecordDao sysChatrecordDao;
    
    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;
    
    @Autowired
    private RedisUtil redisUtil;
    
    /**
     * 通过ID查询所有数据
     *
     * @param id 谁与谁聊天记录表ID
     *
     * @return 实例对象
     */
    @Override
    public List<SysChatrecord> queryAllById(String id) {
        return this.sysChatrecordDao.queryAllById(id);
    }
    
    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     *
     * @return 对象列表
     */
    @Override
    public List<SysChatrecord> queryAllByLimit(int offset, int limit, String id) {
        return this.sysChatrecordDao.queryAllByLimit(offset, limit, id);
    }
    
    /**
     * 搜索内容
     *
     * @param text 搜索内容
     *
     * @return
     */
    @Override
    public List<SysChatrecord> search(String text) {
        return this.sysChatrecordDao.search(text);
    }
    
    /**
     * 新增数据
     *
     * @param sysChatrecord 实例对象
     *
     * @return 实例对象
     */
    @Override
    public boolean insert(SysChatrecord sysChatrecord) {
        
        return this.sysChatrecordDao.insert(sysChatrecord) > 0;
    }
    
    
    /**
     * 通过主键删除数据
     *
     * @param id 主键
     *
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.sysChatrecordDao.deleteById(id) > 0;
    }
    
    
    /**
     * 发送微信通知
     *
     * @param openid   接收人openid
     * @param username 接收人姓名
     * @param type     接收人类型
     */
    @Async
    @Override
    public synchronized void sendWxMessage(String openid, String username, String type) {
        logger.info("给", username, "发送微信通知");
        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        
        
        Map<String, WxMaTemplateData> data = new HashMap<String, WxMaTemplateData>(3);
        
        //备注
        WxMaTemplateData wxMaTemplateData1 = new WxMaTemplateData();
        wxMaTemplateData1.setValue("您有新的消息，请进入师生聊天查看");
        data.put("thing4", wxMaTemplateData1);
        //姓名
        WxMaTemplateData name = new WxMaTemplateData();
        name.setValue(username);
        
        //发送时间
        WxMaTemplateData datetime = new WxMaTemplateData();
        
        datetime.setValue(simpleDateFormat.format(System.currentTimeMillis()));
        
        String appid = null,
                appsecet = null,
                templateId = null;
        
        
        //部分信息设置
        if ("student".equals(type.toLowerCase())) {
            //学生端
            data.put("name2", name);
            data.put("date3", datetime);
            //发送至学生端
            appid = "wx6a41faf108b8ecab";
            appsecet = "6e9c02ef2d83dcd91a2f0e730a9aa358";
            templateId = "p2XKS2Cc9EXo2NGA54buW5rPlrTZOOIPpAQ9ZLJdcBs";
            
            
        } else {
            //管理端
            data.put("name5", name);
            
            //发送至管理端
            appid = "wx78763b2bea2646c2";
            appsecet = "571a3836b6b557d2e7dc1aaeabdc0be2";
            templateId = "kw6rV8MVAe2Jc4P_HFkERg_fmp2mVSf_Tz-Xje4ula8";
        }
        
        
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);
        
        wxMssVo.setPage("pages/chat/bar/bar");
        wxMssVo.setData(data);
        wxMssVo.setTemplate_id(templateId);
        
        //获取消息发送结果
        JSONObject result = wxPushServiceQcl.pushOneUser(
                appid,
                appsecet,
                wxMssVo
        );
        
        //如果发送成功，则记录在redis中，允许每两分钟发送一次
        if (result.getInteger("errcode") == 0) {
            StringBuilder builder = new StringBuilder();
            builder.append(username);
            builder.append("Notice");
            redisUtil.set(builder.toString(), true, 120);
        }
    }
    
    /**
     * 获取指定id的消息个数
     *
     * @param id 指定id
     *
     * @return 消息个数
     */
    @Override
    public Integer countChatRecord(String id) {
        return this.sysChatrecordDao.countChatRecord(id);
    }
}